{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d8e5e290",
   "metadata": {},
   "source": [
    "# with 语句"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d16073d4",
   "metadata": {},
   "source": [
    "- `with` 语句通过在所谓的上下文管理器中封装 `try...finally` 语句的标准用法来简化异常处理。\n",
    "- `with` 语句一般用来管理系统资源的安全获取和释放。`__enter__()` 和 `__exit__()` 这两个方法分别用于获取和释放资源，`with` 语句对它们进行了封装。\n",
    "- 有效地使用 `with` 有助于避免资源泄漏的问题，让代码更加易于阅读。\n",
    "\n",
    "参考：[Python with 语句](https://geek-docs.com/python/python-examples/python-context-manager-and-with-statements.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "03c16d01",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 正常使用一个文件\n",
    "f = open('hello.txt', 'w')\n",
    "try:\n",
    "    f.write('hello world from `try...finally`')\n",
    "finally:\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "d2bd619f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用 with 后\n",
    "with open('hello.txt', 'w') as f:\n",
    "    f.write('hello world from `with`')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
